package com.bstek.tool;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.*;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import org.apache.cordova.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Process;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ilulu on 14-5-30.
 */
public class MainActivity extends BaseSlideMenuActivity implements CordovaInterface {


    TextView ipText, portText, rootText, pageText,logcat_textView;
    Button button;
    List<String> urls=new ArrayList<String>();
    protected CordovaPlugin activityResultCallback = null;
    protected boolean activityResultKeepRunning;
    protected boolean keepRunning = true;
    private final ExecutorService threadPool = Executors.newCachedThreadPool();
    CordovaWebView webView;
    String domain;

    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onContentChanged() {
        super.onContentChanged();
        setSlideRole(R.layout.main);
        setSlideRole(R.layout.setting);
//        setSlideRole(R.layout.log);

        Config.init(this);
        ipText = (TextView) findViewById(R.id.ipText);
        portText = (TextView) findViewById(R.id.portText);
        rootText = (TextView) findViewById(R.id.rootText);
        pageText = (TextView) findViewById(R.id.pageText);
        button = (Button) findViewById(R.id.button);
        webView=(CordovaWebView)findViewById(R.id.browerview);
        initDemoInf();
        webView.loadUrl(Config.getStartUrl());
    }

    private void initDemoInf() {
        SharedPreferences demoInfo = getSharedPreferences("demoInfo", 0);
        setTextEditTexts(ipText, demoInfo.getString("ip", ""));
        setTextEditTexts(portText, demoInfo.getString("port", ""));
        setTextEditTexts(rootText, demoInfo.getString("root", ""));
        setTextEditTexts(pageText, demoInfo.getString("page", ""));

    }


    private void setTextEditTexts(TextView view, String text) {
        view.setText(text);
    }

    private void startPage() {
        saveData();
        String ip=ipText.getText().toString();
        String port=portText.getText().toString();
        String root=rootText.getText().toString();
        String page=pageText.getText().toString();

        StringBuffer url=new StringBuffer("http://");
        if(!ip.isEmpty()){
            url.append(ip);
        }
        if(!port.isEmpty()){
            url.append(":"+port);
        }
        if(!root.isEmpty()){
            url.append("/"+root);
        }
        if(!page.isEmpty()){
            url.append("/"+page);
        }

        domain="http://";
        if(!ip.isEmpty()){
            domain+=ip;
        }
        if(!port.isEmpty()){
            domain+=":"+port;
        }
        if(!root.isEmpty()){
            domain+="/"+root;
        }

        webView.loadUrl(url.toString(),100000);
        webView.setWebViewClient(new CordovaWebViewClient(this,webView){
            @Override
            public void onPageFinished(WebView view, String url) {
                String urlReal = url.split("#")[0];
                if(!urls.contains(urlReal)) {
                    String js = "javascript:var a = document.createElement(\"script\");\n" +
                            "            a.type = \"text/javascript\";\n" +
                            "            a.src = '"+domain+"/cordovaJS/platform/android/cordova.js';\n" +
                            "            var head = document.getElementsByTagName(\"head\")[0];\n" +
                            "            head.appendChild(a);";
                    view.loadUrl(js);
                    String js2 = "javascript:var ab = document.createElement(\"script\");\n" +
                            "            ab.type = \"text/javascript\";\n" +
                            "            ab.src = '"+domain+"/cordovaJS/bn.js';\n" +
                            "            var head = document.getElementsByTagName(\"head\")[0];\n" +
                            "            head.appendChild(ab);";
                    view.loadUrl(js2);
                    urls.add(urlReal);
                    super.onPageFinished(view, url);
                }
            }
        });

    }

    public void openPage(View view) {
        startPage();
        getSlideMenu().close(true);
    }

    private void saveData() {
        SharedPreferences demoInfo = getSharedPreferences("demoInfo", 0);
        demoInfo.edit().putString("ip", ipText.getText().toString()).commit();
        demoInfo.edit().putString("port", portText.getText().toString()).commit();
        demoInfo.edit().putString("root", rootText.getText().toString()).commit();
        demoInfo.edit().putString("page", pageText.getText().toString()).commit();
    }

    @Override
    public void setActivityResultCallback(CordovaPlugin plugin) {
        this.activityResultCallback = plugin;
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public Object onMessage(String id, Object data) {
        return null;
    }

    @Override
    public ExecutorService getThreadPool() {
        return threadPool;
    }

    /**
     * Launch an activity for which you would like a result when it finished. When this activity exits,
     * your onActivityResult() method is called.
     *
     * @param command     The command object
     * @param intent      The intent to start
     * @param requestCode The request code that is passed to callback to identify the activity
     */
    public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
        this.activityResultCallback = command;
        this.activityResultKeepRunning = this.keepRunning;


        // If multitasking turned on, then disable it for activities that return results
        if (command != null) {
            this.keepRunning = false;
        }


        // Start activity
        super.startActivityForResult(intent, requestCode);

    }


    @Override
/**
 * Called when an activity you launched exits, giving you the requestCode you started it with,
 * the resultCode it returned, and any additional data from it.
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param data              An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        CordovaPlugin callback = this.activityResultCallback;
        if (callback != null) {
            callback.onActivityResult(requestCode, resultCode, intent);
        }
    }

    @Override
    protected void onDestroy() {
        webView.removeAllViews();
        webView.handleDestroy();
        finish();
        super.onDestroy();
    }
}